package com.swxc.smartorder.ui.activity

import android.graphics.Color
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import com.google.gson.reflect.TypeToken
import com.lzy.okgo.model.HttpParams
import com.swxc.smartorder.R
import com.swxc.smartorder.adapter.AdapterRecord
import com.swxc.smartorder.app.ConfigSPS
import com.swxc.smartorder.app.GlobalAPI
import com.swxc.smartorder.entity.BackEntity
import com.swxc.smartorder.entity.CommonData
import com.swxc.smartorder.entity.OrderDetailEntity
import com.swxc.smartorder.entity.Record
import com.swxc.smartorder.event.EventUtil
import com.swxc.smartorder.event.SimpleEvent
import com.swxc.smartorder.network.NetworkHelper
import com.swxc.smartorder.ui.base.BaseActivity
import com.swxc.smartorder.ui.dialog.SignOutDialog
import com.swxc.smartorder.utils.*
import kotlinx.android.synthetic.main.activity_order_detail.*
import kotlinx.android.synthetic.main.layout_order_content.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import kotlin.math.min


/**
 * 工单详情页面
 */
class OrderDetailActivity : BaseActivity(), View.OnClickListener {

    companion object {
        const val REQUEST_SUCCESS: Int = 0x0001
    }

    private var mHeaderView: View? = null
    private var mAdapter: AdapterRecord? = null
    private var mList: MutableList<Record>? = null
    private var mHelper: NetworkHelper? = null

    private val signOutDialog = SignOutDialog()
    private var mOrderId: Long = 0
    private var mStaffId: Long = 0
    private var mDistance = 0
    private var maxDistance: Int? = null
    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.iv_back -> {
                finish()
            }
            R.id.btn_submit -> {

                handleOrder("ACCEPTED")
            }
            R.id.ll_transfer -> {

                val bundle = Bundle()
                bundle.putLong("mOrderId", mOrderId)
                readyGo(ContactListActivity::class.java, bundle)

            }

            R.id.ll_finish -> {


                val bundle = Bundle()
                bundle.putString("strTitle", "您确定要完结此工单吗？")
                bundle.putString("strContent", "在确认完结工单前请务必确认工单任务是否处理完毕。")
                bundle.putString("strSure", "确认完结")
                bundle.putString("strCancel", "取消")
                signOutDialog.arguments = bundle
                signOutDialog.show(supportFragmentManager, "acceptDialog")
                signOutDialog.setOnSureClickListener { handleOrder("FINISH") }

            }
            R.id.edt_back_message, R.id.tv_back -> {
                val bundle = Bundle()
                bundle.putLong("orderID", mOrderId)
                bundle.putLong("STAFF_ID", mStaffId)
                readyGo(BackMessageActivity::class.java, bundle)
            }
        }
    }


    /**
     *
     */
    private fun handleOrder(type: String) {
        if (signOutDialog.isVisible) {
            signOutDialog.dismiss()
        }
        mHelper?.handOrder("", "", mOrderId, mStaffId, type, object : NetworkHelper.NetWorkHelperBack {
            override fun requestSuccess(json: String) {


                val fromJson = JsonUtil.fromJson<BackEntity>(json, BackEntity::class.java)
                        ?: return
                when (fromJson.responseCode) {
                    1001 -> {

                        if (type == "ACCEPTED") {
                            initData()
                            val toastUtil = ToastUtil(mContext, true, ToastUtil.STATUS_SUCCESS, "接单成功")
                            toastUtil.show(2000)
                            llayout_handle.visibility = View.VISIBLE
                            llayout_accept.visibility = View.GONE
                            llayout_reply.visibility = View.GONE
                        } else {
                            val toastUtil = ToastUtil(mContext, true, ToastUtil.STATUS_SUCCESS, "已完结工单")
                            toastUtil.show(2000)
                            initData()

                        }
                    }
                    else -> {
                        if (type == "ACCEPTED") {
                            val toastUtil = ToastUtil(mContext, false, ToastUtil.STATUS_ERROR, "接单失败")
                            toastUtil.show(2000)
                        } else {
                            val toastUtil = ToastUtil(mContext, false, ToastUtil.STATUS_ERROR, "工单完结失败")
                            toastUtil.show(2000)
                        }
                    }
                }
            }

            override fun requestFail() {
                Log.e("test", "失败")
            }
        })
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_order_detail)
        EventUtil.getInstance().register(this)


        initBundleData()
        initViewAndEvent()
        initData()
    }

    override fun onDestroy() {
        EventUtil.getInstance().unregister(this)
        super.onDestroy()
    }

    override fun onRestart() {
        super.onRestart()
        initData()
    }

    private fun initData() {
        val httpParams = HttpParams()
        httpParams.put("id", mOrderId)
        mHelper?.getRequest(GlobalAPI.orderDetail, httpParams, object : NetworkHelper.NetWorkHelperBack {
            override fun requestSuccess(json: String) {


                val type = object : TypeToken<CommonData<OrderDetailEntity>>() {}.type

                val fromJson = JsonUtil.fromJson<CommonData<OrderDetailEntity>>(json, type)
                when (fromJson.responseCode) {
                    1001 -> {
                        EventUtil.getInstance().post(SimpleEvent(SimpleEvent.ORDER_DETAIL, REQUEST_SUCCESS, fromJson.data))
                    }
                }
            }

            override fun requestFail() {}
        })


    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun updateUi(simpleEvent: SimpleEvent) {
        if (simpleEvent.mEventType != SimpleEvent.ORDER_DETAIL) {
            return
        }
        when (simpleEvent.mEventValue) {
            REQUEST_SUCCESS -> {
                val data: OrderDetailEntity = simpleEvent.data as OrderDetailEntity
                initUI(data)
            }
        }
    }


    /**
     *
     */
    private fun initUI(data: OrderDetailEntity) {


        if (data.record.isNotEmpty()) {
            mList?.clear()
            mList?.addAll(data.record)
            mAdapter?.notifyDataSetChanged()
        }
        tv_date.text = DateUtil.getTimeFormatString(data.detail.createTime)


        //设置发起人信息
        tv_name.text = data.detail.launcherName
        tv_phone.text = data.detail.launcherMobile
        tv_address.text = data.detail.receivingAddress

        //顶部订单消息
        when (data.detail.priorityLevel) {
            "NORMAL" -> {
                tv_status.text = "一般"
                tv_status.setTextColor(Color.parseColor("#80cb9a"))
            }
            "URGENT" -> {
                tv_status.text = "紧急"
                tv_status.setTextColor(Color.parseColor("#fb5f5f"))
            }
            "VERY_URGENT" -> {
                tv_status.text = "非常紧急"
                tv_status.setTextColor(Color.parseColor("#fb5f5f"))
            }
        }
        page_title.text = data.detail.title
        tv_title.text = data.detail.categoryName
        tv_number.text = data.detail.number
        tv_content.text = data.detail.title
        //问题描述
        tv_desc.text = data.detail.content

        //图片
        if (data.detail.images.isEmpty()) {
            clayout_image.visibility = View.GONE
        } else {
            val linearLayout = LinearLayout(mContext)
            var imageList: ArrayList<String>? = null
            imageList = ArrayList()
            data.detail.images.forEach { imageList.add(it.thumbImageURL) }


            data.detail.images.forEachIndexed { index, imageEntity ->
                val imageView = ImageView(mContext)
                ImageDisplayUtil.showImageView(mContext, imageEntity.thumbImageURL, imageView)
                linearLayout.addView(imageView)
                imageView.setOnClickListener {
                    val bundle = Bundle()
                    bundle.putInt("index", index)
                    bundle.putStringArrayList("images", imageList)
                    readyGo(PreviewActivity::class.java, bundle)
                }

            }
            image_view_layout.addView(linearLayout)

        }


        //设置底部控件是否可见
        when (data.detail.status) {
            "ACCEPTED" -> {
                llayout_has_compete.visibility = View.GONE
                llayout_accept.visibility = View.GONE
                if (data.detail.staffId == mStaffId) {
                    llayout_handle.visibility = View.VISIBLE
                    llayout_reply.visibility = View.GONE
                } else {
                    llayout_reply.visibility = View.VISIBLE
                    llayout_handle.visibility = View.GONE

                }
            }
            "FINISHED" -> {
//                llayout_has_compete.visibility = View.VISIBLE
//                tv_compete.text = "已完结"
                ll_bottom.visibility = View.GONE

            }
            "UNTREATED" -> {
                llayout_has_compete.visibility = View.GONE
                llayout_handle.visibility = View.GONE
                llayout_reply.visibility = View.VISIBLE
                if (data.acceptView) {
                    llayout_accept.visibility = View.VISIBLE
                } else {
                    llayout_accept.visibility = View.GONE
                }
            }
        }

    }

    private fun initViewAndEvent() {
        mHelper = NetworkHelper(mContext, supportFragmentManager)
        maxDistance = mContext.let { DisplayUtil.dip2px(it, 56f) }
        iv_back.setOnClickListener(this)
        btn_submit.setOnClickListener(this)
        ll_transfer.setOnClickListener(this)
        ll_finish.setOnClickListener(this)
        tv_back.setOnClickListener(this)
        edt_back_message.setOnClickListener(this)
        mStaffId = AppSharePreferenceMgr.get(mContext, ConfigSPS.STAFF_ID, 0L) as Long
        mList = ArrayList()
        mAdapter = AdapterRecord(mList)

        mHeaderView = layoutInflater.inflate(R.layout.layout_order_content, null, false)

        mAdapter?.addHeaderView(mHeaderView)
        rv_record.layoutManager = LinearLayoutManager(this)
        rv_record.adapter = mAdapter
        rv_record.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                mDistance += dy

                val min = min(a = mDistance, b = maxDistance!!)
                val percent = min * 1f / maxDistance!!
                val alpha: Int = (percent * 255).toInt()
                page_title.setTextColor(Color.argb(alpha, 50, 60, 73))
            }
        })


    }


    private fun initBundleData() {

        mOrderId = intent.extras.get("orderID") as Long
    }
}
